import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import router from '@/router/index'

// const baseURL = "http://172.16.100.161/api"
//const baseURL = process.env.VUE_APP_BASE_API
// const baseURL = "/api"
 const baseURL = ''
// create an axios instance
const service = axios.create({
  baseURL: baseURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['JSESSIONID'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  async response => {
    const res = response.data
    switch (res.code) {
      case 400: 
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        break 
      case 401: //用户名非法
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
        break
      case 408://登陆超时 重新登陆
        await store.dispatch('user/logout') //清除所有登陆信息，并解决无限循环问题
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
        router.replace({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath
          }
        })
        break
      case 500:
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
        break
      default:  //其他情况，正常返回
        return res
      //return Promise.reject(new Error(res.message || 'Error')) // 其它错误，直接抛出错误提示
    }
  },
  error => {
    const errMsg = error.message
    if (error && error.response && error.response.status) {
      switch (error.response.status) {
        // 请求返回的错误妈需要与后台开发人员协商好，以便更快的定位错误。
        case 401: // 用户未登录
          Message.error({
            message: '未授权，请登录'
          })
          router.replace({
            path: '/login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
          break
        case 403: // token过期
          Message.error({
            message: errMsg || 'token过期'
          })
          setTimeout(() => {
            router.replace({
              path: '/login',
              query: {
                redirect: router.currentRoute.fullPath
              }
            })
          }, 1000)
          break
        case 404: // 请求错误
          Message.error({
            message: errMsg || '请求地址出错'
          })
          break
        case 500:
          Message.error({
            message: `服务器内部错误:${errMsg}`
          })
          break
        default: // 其它错误，直接抛出错误提示
          Message.error({
            message: errMsg
          })
      }
    } else {
      Message.error({
        message: errMsg || '网络错误'
      })
    }
    return Promise.reject(error.response)
  }
)

export default service
